<template>
    <el-row class="contain-box">
        <site-nav/>
        <div class="view-body">
            <el-row>
                <el-form class="inline-form" inline>
                    <el-form-item label="用户名">
                        <el-input @clear="search" clearable placeholder="请输入用户名" v-model="params.usernameLike"/>
                    </el-form-item>
                    <el-form-item label="姓名">
                        <el-input @clear="search" clearable placeholder="请输入姓名" v-model="params.nameLike"/>
                    </el-form-item>
                    <el-form-item label="部门">
                        <dept-tree-selecter :show-none="true" v-model="params.departmentId"/>
                    </el-form-item>
                    <el-form-item label="职位">
                        <el-select clearable filterable placeholder="请选择" v-model="params.dutyId">
                            <el-option :value="null" label="不限"/>
                            <el-option :key="item.dutyId" :label="item.dutyName" :value="item.dutyId"
                                       v-for="item in duties"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="禁用">
                        <el-select clearable filterable placeholder="请选择" v-model="params.enabled">
                            <el-option :value="null" label="不限"/>
                            <el-option :value="false" label="是"/>
                            <el-option :value="true" label="否"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="search" icon="el-icon-search" type="primary">搜索</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-form class="inline-form" inline>
                    <el-form-item>
                        <el-button @click="addUser" type="primary"><i class="el-icon-plus el-icon--left"/>添加用户
                        </el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="batchAddPosition" :disabled="currentUserIds.length === 0">批量添加职位
                        </el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="batchDeletePosition" :disabled="currentUserIds.length === 0">批量删除职位
                        </el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="exportExcel">导出Excel</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <el-col>
                    <el-table :data="list" border size="small" @selection-change="handleSelectionChange">
                        <el-table-column fixed type="selection" width="40"/>
                        <el-table-column align="center" fixed type="expand" width="40">
                            <template slot-scope="scope">
                                <el-form label-width="100px" size="small">
                                    <el-form-item label="性别">
                                        <span>{{gender[scope.row.gender]}}</span>
                                    </el-form-item>
                                    <el-form-item label="注册时间">
                                        <span>{{scope.row.registrationTime | dateFormat}}</span>
                                    </el-form-item>
                                    <el-form-item label="最后登录">
                                        <span>{{scope.row.lastLoginTime | dateFormat}}</span>
                                    </el-form-item>
                                    <el-form-item label="禁用">
                                        <commons-enable :value="!scope.row.enabled"/>
                                    </el-form-item>
                                    <el-form-item label="管理员" v-isAdmin>
                                        <commons-enable :value="scope.row.admin"/>
                                    </el-form-item>
                                    <el-form-item label="职位列表">
                                        <el-tag v-for="(item) in positionMap[scope.row.userId]"
                                                :key="`${item.userId}_${item.departmentId}_${item.dutyId}`"
                                                class="position" type="success"
                                                v-if="item.dutyId === '1'">
                                            {{item.department.departmentName}} - {{item.duty.dutyName}}
                                        </el-tag>
                                        <el-tag v-for="(item) in positionMap[scope.row.userId]"
                                                :key="`${item.userId}_${item.departmentId}_${item.dutyId}`"
                                                class="position" type="warning"
                                                v-if="item.dutyId === '2'">
                                            {{item.department.departmentName}} - {{item.duty.dutyName}}
                                        </el-tag>
                                        <el-tag v-for="(item) in positionMap[scope.row.userId]"
                                                :key="`${item.userId}_${item.departmentId}_${item.dutyId}`"
                                                class="position"
                                                v-if="item.dutyId !== '1' && item.dutyId !== '2'">
                                            {{item.department.departmentName}} - {{item.duty.dutyName}}
                                        </el-tag>
                                    </el-form-item>
                                </el-form>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" fixed label="用户ID" prop="userId" width="150"/>
                        <el-table-column align="center" label="头像" width="70">
                            <template slot-scope="scope">
                                <user-avatar v-model="scope.row.avatar"/>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="姓名" min-width="80" prop="name"/>
                        <el-table-column align="center" label="用户名" min-width="80" prop="username"/>
                        <el-table-column align="center" label="电话" min-width="100" prop="phone"/>
                        <el-table-column align="center" label="邮箱" min-width="160" prop="email"/>
                        <el-table-column align="center" label="部门" prop="departmentName"/>
                        <el-table-column align="center" label="主职位" prop="mainDutyName"/>
                        <el-table-column fixed="right" label="操作" width="230">
                            <template slot-scope="scope">
                                <el-button :disabled="scope.row.admin && !isAdmin" @click="toPositionPage(scope.row)"
                                           size="mini"
                                           type="primary">职位
                                </el-button>
                                <el-button :disabled="scope.row.admin && !isAdmin" @click="updateUser(scope.row)"
                                           size="mini"
                                           type="primary">修改
                                </el-button>
                                <el-dropdown class="dropdown" size="small">
                                    <el-button size="mini" type="primary">
                                        操作<i class="el-icon-arrow-down el-icon--right"/>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item :disabled="$isDefaultAvatar(scope.row.avatar)"
                                                          @click.native="deleteAvatar(scope.row)">删除头像
                                        </el-dropdown-item>
                                        <el-dropdown-item @click.native="deleteUser(scope.row)"
                                                          divided v-if="isAdmin && scope.row.userId !== currentUserId">
                                            <el-link :underline="false" type="danger">删除用户</el-link>
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row>
                <el-col class="pagination">
                    <el-pagination :current-page="params.pageId" :page-size="params.pageSize" :total="count"
                                   @current-change="currentChange" background layout="total, prev, pager, next"/>
                </el-col>
            </el-row>
        </div>
        <el-dialog :before-close="dialogClose" :title="dialog.isAdd ? '新增用户' : '修改用户'" :visible.sync="dialog.show"
                   class="dialog">
            <el-form :model="info" :rules="rules" label-width="120px" ref="form" size="small">
                <el-form-item :required="dialog.isAdd" label="用户名" prop="username">
                    <template v-if="dialog.isAdd">
                        <el-input placeholder="请输入用户名" type="text" v-model="info.username" maxlength="100"/>
                    </template>
                    <template v-else>{{info.username}}</template>
                </el-form-item>
                <el-form-item :required="dialog.isAdd" label="密码" prop="password">
                    <el-input :placeholder="dialog.isAdd ? '请输入密码' : '不修改密码请留空'" type="password"
                              v-model="info.password"/>
                </el-form-item>
                <el-form-item label="姓名" prop="name" required>
                    <el-input placeholder="请输入姓名" type="text" v-model="info.name" maxlength="100"/>
                </el-form-item>
                <el-form-item :required="dialog.isAdd" label="部门" prop="departmentId">
                    <dept-tree-selecter v-model="info.departmentId"/>
                </el-form-item>
                <el-form-item label="主职位" prop="mainDutyId">
                    <el-select clearable filterable placeholder="请选择" v-model="info.mainDutyId">
                        <el-option label="无" value="0"/>
                        <el-option :key="item.dutyId"
                                   :label="item.dutyName"
                                   :value="item.dutyId"
                                   v-for="item in duties"
                                   v-if="!$isSystemDuty(item.dutyId)"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="头像">
                    <user-avatar class="avatar-edit" v-model="avatarCache"/>
                    <upload-single :on-success="avatarUploadHandler" accept="image/*" class="avatar-uploader"
                                   path="avatar"/>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="info.gender">
                        <el-radio :key="key" :label="key" v-for="(text, key) in gender">{{text}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="电子邮箱">
                    <el-input placeholder="请输入电子邮箱" type="email" v-model="info.email" maxlength="100"/>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input placeholder="请输入电话" type="tel" v-model="info.phone" maxlength="100"/>
                </el-form-item>
                <el-form-item label="帐号禁用">
                    <el-radio-group v-model="info.enabled">
                        <el-radio :label="true">否</el-radio>
                        <el-radio :label="false">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="管理员权限" v-isAdmin>
                    <el-radio-group v-model="info.admin">
                        <el-radio :label="false">否</el-radio>
                        <el-radio :label="true">是</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="dialogClose" size="mini">取 消</el-button>
                <el-button :loading="dialog.submitting" @click="dialogSubmit" size="mini" type="primary">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :before-close="positionDialogClose" :title="positionDialog.isAdd ? '批量增加职位' : '批量删除职位'"
                   :visible.sync="positionDialog.show"
                   class="dialog">
            <el-form label-width="120px" ref="form" size="small">
                <el-form-item label="部门">
                    <dept-tree-selecter v-model="departmentDuty.departmentId" @choose="chooseDepartment"/>
                </el-form-item>
                <el-form-item label="职位">
                    <el-select clearable filterable placeholder="请选择" v-model="currentDuty" value-key="dutyId">
                        <el-option :key="item.dutyId" :label="item.dutyName"
                                   :value="item" v-for="item in duties" v-if="!$isSystemDuty(item.dutyId)"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="职位列表">
                    <el-tag v-for="(item) in departmentDuties"
                            :key="`${item.departmentId}_${item.dutyId}`"
                            class="position">
                        {{item.departmentName}} - {{item.dutyName}}
                    </el-tag>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button :loading="positionDialog.submitting" @click="addDepartmentDuty" size="mini" type="primary">添 加</el-button>
                <el-button @click="positionDialogClose" size="mini">取 消</el-button>
                <el-button :loading="positionDialog.submitting" @click="positionDialogSubmit" size="mini" type="primary"
                           :disabled="departmentDuties.length === 0"
                >提 交</el-button>
            </div>
        </el-dialog>
    </el-row>
</template>
<script lang="ts">
  import {ID, PARAMS} from '@/api/http';
  import DepartmentApi from '@/api/user/departmentApi';
  import DutyApi from '@/api/user/dutyApi';
  import PositionApi from '@/api/user/positionApi';
  import UserApi from '@/api/user/userApi';
  import AvatarModule from '@/store/modules/avatar';
  import Department from '@/structure/department';
  import DepartmentDuty from '@/structure/departmentDuty';
  import DialogInfo from '@/structure/dialogInfo';
  import Duty from '@/structure/duty';
  import FileInfo from '@/structure/fileInfo';
  import FormRules from '@/structure/formRules';
  import {GenderMap} from '@/structure/gender';
  import Position from '@/structure/position';
  import PositionBatchRequest from '@/structure/positionBatchRequest';
  import User from '@/structure/user';
  import download from '@/utils/download';
  import UserUtil from '@/utils/user';
  import {ElForm} from 'element-ui/types/form';
  import {Component, Vue} from 'vue-property-decorator';

  @Component
  export default class Page extends Vue {

    public isAdmin: boolean = false;
    public currentUserId?: ID;
    public departmentList: Department[] = [];
    public duties: Duty[] = [];
    public userIds: ID[] = [];
    public positionMap: { [key: string]: Position[] } = {};
    public list: User[] = [];
    public currentUserIds: ID[] = [];
    public departmentDuties: DepartmentDuty[] = [];
    public currentDepartment: Department | '' = '';
    public currentDuty: Duty | '' = '';
    public departmentDuty: DepartmentDuty = new DepartmentDuty();
    public count: number | null = null;
    public params: PARAMS = {
      pageId: 1,
      usernameLike: null,
      nameLike: null,
      departmentId: null,
      dutyId: null,
      enabled: null
    };
    public dialog: DialogInfo = new DialogInfo();
    public positionDialog: DialogInfo = new DialogInfo();
    public info: User = new User();
    public avatarCache: string = '';
    public rules: FormRules = {
      username: [
        {
          required: true,
          message: '请输入用户名'
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码'
        }
      ],
      name: [
        {
          required: true,
          message: '请输入姓名'
        }
      ],
      departmentId: [
        {
          required: true,
          message: '请选择部门'
        }
      ]
    };
    public gender = GenderMap;

    public created(): void {
      const user = UserUtil.getUser();
      this.isAdmin = user.admin;
      this.currentUserId = user.userId;
      this.$parseParams(this.params, this.$route);

      DepartmentApi.all().then((res) => {
        this.departmentList = res;
      });
      DutyApi.all().then((res) => {
        this.duties = res;
      });
      UserApi.findList(this.params).then((res) => {
        this.list = res.list;
        this.count = res.count;
        this.getPositionData();
      });
    }

    public search(): void {
      this.currentChange(1);
    }

    public getDataList(): void {
      const str = this.$formatParamsUrl(this.params);
      UserApi.findList(this.params).then((res) => {
        this.$router.push(str);
        this.list = res.list;
        this.count = res.count;
        this.getPositionData();
      });
    }

    public exportExcel(): void {
      UserApi.exportExcel(this.params).then((blob) => {
        download(blob, '用户列表 ' + this.$moment(Date.now()).format('YYYY-MM-DD-HH-mm-ss') + '.xlsx');
      });
    }

    public getPositionData(): void {
      this.userIds = this.list.map((user) => user.userId);
      PositionApi.queryByUserIds(this.userIds).then((positionMap) => {
        this.positionMap = positionMap;
      });
    }

    public currentChange(val: number): void {
      this.params.pageId = val;
      this.getDataList();
    }

    public addUser(): void {
      this.rules.password[0].required = true;

      this.dialog.isAdd = true;
      this.dialog.show = true;

      this.info = new User();
      this.avatarCache = '';

      this.$nextTick(() => {
        (this.$refs.form as ElForm).clearValidate();
      });
    }

    public updateUser(info: User): void {
      this.info = {...info} as User;

      this.rules.password[0].required = false;
      this.rules.departmentId[0].required = false;
      this.dialog.isAdd = false;
      this.dialog.show = true;
      this.avatarCache = info.avatar ? info.avatar : '';

      this.$nextTick(() => {
        (this.$refs.form as ElForm).clearValidate();
      });
    }

    public dialogClose(): void {
      this.dialog.show = false;
      (this.$refs.form as ElForm).resetFields();
    }

    public dialogSubmit(): void {
      if (this.dialog.submitting) {
        return;
      }

      (this.$refs.form as ElForm).validate((valid) => {
        if (!valid) {
          return;
        }

        this.dialog.submitting = true;

        const func = this.dialog.isAdd ? UserApi.save : UserApi.update;
        const msg = this.dialog.isAdd ? '添加用户成功' : '编辑用户成功';

        func.call(UserApi, this.info).then(() => {
          this.getDataList();
          this.dialogClose();
          this.dialog.submitting = false;
          this.$message.success(msg);
        }).catch(() => {
          this.dialog.submitting = false;
        });
      });
    }

    public avatarUploadHandler(res: FileInfo): void {
      this.info.avatar = res.webPath;
      this.avatarCache = res.webPath;
    }

    public toPositionPage(info: User): void {
      this.$router.push({
        name: 'User_User_Position',
        params: {
          userId: '' + info.userId
        },
        query: {
          name: '' + info.name,
          username: '' + info.username,
          departmentId: '' + info.departmentId,
          mainDutyId: '' + info.mainDutyId
        }
      });
    }

    public deleteUser(info: User): void {
      this.$confirm('是否删除改用户？', '删除用户', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        UserApi.delete(info.userId).then(() => {
          this.getDataList();
          this.$message.success('删除成功!');
        });
      });
    }

    public deleteAvatar(info: User): void {
      UserApi.deleteAvatar(info.userId).then((res) => {
        info.avatar = res.avatar;
        this.$message.success('删除头像成功!');
        if (info.userId === UserUtil.getUser().userId) {
          UserUtil.setUser(res);
          AvatarModule.change(res.avatar);
        }
      });
    }

    public handleSelectionChange(list: User[]) {
      if (list && list.length > 0) {
        this.currentUserIds = list.map((user) => user.userId);
      } else {
        this.currentUserIds = [];
      }
    }

    public batchAddPosition(): void {
      this.positionDialog.isAdd = true;
      this.positionDialog.show = true;
    }

    public batchDeletePosition(): void {
      this.positionDialog.isAdd = false;
      this.positionDialog.show = true;
    }

    public positionDialogClose(): void {
      this.positionDialog.show = false;
      this.departmentDuty = new DepartmentDuty();
      this.departmentDuties = [];
      this.currentDepartment = '';
      this.currentDuty = '';
    }

    public positionDialogSubmit(): void {
      if (this.positionDialog.submitting) {
        return;
      }

      this.positionDialog.submitting = true;

      const request = new PositionBatchRequest();
      request.userIds = this.currentUserIds;
      request.departmentDuties = this.departmentDuties;

      const func = this.positionDialog.isAdd ? PositionApi.batchSave : PositionApi.batchDelete;
      const msg = this.positionDialog.isAdd ? '批量添加职位成功' : '批量删除职位成功';

      func.call(PositionApi, request).then(() => {
        this.getPositionData();
        this.positionDialogClose();
        this.positionDialog.submitting = false;
        this.$message.success(msg);
      }).catch(() => {
        this.positionDialog.submitting = false;
      });
    }

    public addDepartmentDuty() {
      if (this.currentDuty && this.currentDepartment) {
        this.departmentDuties.push({
          departmentId: this.currentDepartment.departmentId,
          departmentName: '' + this.currentDepartment.departmentName,
          dutyId: this.currentDuty.dutyId,
          dutyName: '' + this.currentDuty.dutyName
        });
      }
    }

    public chooseDepartment(department: Department): void {
      this.currentDepartment = department;
    }
  }
</script>
<style lang="scss" scoped>
    .avatar-edit {
        display: inline-block;
    }

    .avatar-uploader {
        margin-left: 20px;
        display: inline-block;
    }

    .dropdown {
        margin-left: 10px;
    }

    .position {
        margin-right: 10px;

        &:last-child {
            margin-right: 0;
        }
    }
</style>
